package com.sjy.qqfile.controller;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sjy.bean.User;
import com.sjy.dao.userdao;
import com.sjy.qqfile.QQentity.QQUser;

@Controller
public class UserController {
	@Autowired
	public userdao userdao;

	/**
	 * QQ会掉路径
	 */
	@RequestMapping("/qq")
     public String panduanbangding(@AuthenticationPrincipal UsernamePasswordAuthenticationToken userAuthentication) {
		 
		QQUser user = (QQUser) userAuthentication.getPrincipal();
		String openidString=user.getOpenId();
		User user2=userdao.findByOpenId(openidString);
		if(user2==null) {
			return "bangding";
			
		}else {
			setContextHolder(user2);
			return "redirect:/main";
		}
		
	}

    @GetMapping("/user")
    public String user(@AuthenticationPrincipal UsernamePasswordAuthenticationToken userAuthentication, Model model){
        QQUser user = (QQUser) userAuthentication.getPrincipal();
        model.addAttribute("username", user.getNickname());
        model.addAttribute("avatar", user.getAvatar());
        return "user/user";
    }

    private void setContextHolder(User user) {
    	UserDetails webUserDetails = user;
        Authentication authentication = new UsernamePasswordAuthenticationToken(webUserDetails,user.getUsername(), new ArrayList<GrantedAuthority>());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
}
